﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Security.Cryptography;

namespace Sub.Function
{
    public class Associate
    {
        /// <summary>
        /// get base service url
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetAbsUrl(string path)
        {
            try
            {
                var r = HttpContext.Current.Request;
                string ret = "";
                string http = "http";
                if (r.ServerVariables["HTTPS"] == "on")
                {
                    http = "https";
                }
                if (r.ServerVariables.AllKeys.Contains("server_port"))
                {
                    ret = http + "://" + r.ServerVariables["HTTP_HOST"] + ":" + r.ServerVariables["server_port"] + VirtualPathUtility.ToAbsolute(path);

                }
                else
                {
                    ret = http + "://" + r.ServerVariables["HTTP_HOST"] + VirtualPathUtility.ToAbsolute(path);
                }
                return ret;
            }
            catch (Exception ex)
            {

                throw (ex);
            }
        }
        /// <summary>
        /// convert url to absolute address
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ConvertUrl(string url)
        {
            if (url.IndexOf("~/") > -1)
            {
                return GetAbsUrl(url);
            }
            else
            {
                return url;
            }
        }
        /// <summary>
        /// read an ascx file and return to html string value
        /// </summary>
        /// <param name="file">ascx file</param>
        /// <returns>content</returns>
        public static string Render(string file)
        {
            try
            {
                UserControl control = new UserControl();
                control = control.LoadControl(file) as UserControl;
                StringBuilder sb = new StringBuilder();
                control.Visible = true;
                control.DataBind();
                using (StringWriter sw = new StringWriter(sb))
                {
                    using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
                    {
                        control.RenderControl(textWriter);
                    }
                }
                control.Visible = false;
                return sb.ToString();
            }
            catch (Exception ex)
            {

                throw (new Exception(file + "," + ex.Message));
            }
        }
        /// <summary>
        /// decrypt string token
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        const string mask = "=/%&+-*";
        private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");
        public static string Decrypt(string text)
        {
            return DecryptStringAES(text, "123451212");
        }
        public static string Decrypt(string text, string SecretKey)
        {
            return DecryptStringAES(text, SecretKey);
        }

        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText)) return "";
            byte[] bff = UnicodeEncoding.UTF8.GetBytes(mask);
            for (int i = 0; i < bff.Length; i++)
            {
                cipherText = cipherText.Replace("_" + bff[i].ToString() + "_", mask[i].ToString());
            }
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.                
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }
        /// <summary>
        /// Encrypt data
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Encrypt(string text)
        {
            return EncryptStringAES(text, "123451212");
        }
        public static string Encrypt(string text, string SecretKey)
        {
            return EncryptStringAES(text, SecretKey);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="sharedSecret"></param>
        /// <returns></returns>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            //if (string.IsNullOrEmpty(plainText))
            //    throw new ArgumentNullException("plainText");
            //if (string.IsNullOrEmpty(sharedSecret))
            //    throw new ArgumentNullException("sharedSecret");

            string outStr = null;                       // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            byte[] bff = UnicodeEncoding.UTF8.GetBytes(mask);
            for (int i = 0; i < bff.Length; i++)
            {
                outStr = outStr.Replace(mask[i].ToString(), "_" + bff[i].ToString() + "_");
            }
            return outStr;
        }
    }
}
